import type { FormInstance } from 'element-plus'
import type { NoticeItemType, TemplatePropsType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElButton,
  ElIcon,
  ElMessage,
  ElRadioGroup,
  ElRadio,
  ElCascader
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'SystemUserOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: TemplatePropsType, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<NoticeItemType>({})
    const state = reactive({
      userTreeOpt: []
    })
    const propsCascader = {
      multiple: true,
      checkStrictly: true,
      value: 'id',
      label: 'title',
      disabled: 'hasChildren'
    }
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }
    //  选择用户
    const cascaderChange = (value: string[]) => {
      formValues.userIds = []
      formValues.names = []
      if (value.length > 0) {
        for (let i = 0; i < value.length; i++) {
          const element = value[i]
          formValues.userIds.push(element[element.length - 1])
        }
        getUserName(state.userTreeOpt)
      }
    }
    //  过去用户名称
    const getUserName = (value?: any) => {
      if (value.length > 0) {
        value.forEach((item: any) => {
          if (formValues.userIds.indexOf(item.id) !== -1) {
            formValues.names.push(item.title)
          }
          if (item.children) {
            getUserName(item.children)
          }
        })
      }
    }

    // 提交表单
    const handleSubmitForm = (value: number) => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        if (formValues.userIds) {
          formValues.userIds = formValues.userIds?.join(',')
          formValues.userNames = formValues.names?.join(',')
        }
        const params = { ...formValues }

        const res = await store.dispatch(
          value === 1 ? 'notice/NoticeAddPost' : 'notice/NoticePushNoticePost',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        }
      })
    }
    //  用户组织树
    const userTreeAjax = async () => {
      const { data, code } = await store.dispatch('notice/GetDeptUserTreeGet')
      if (code === 200) {
        state.userTreeOpt = data
      }
    }
    onMounted(() => {
      const { type } = props
      if (props.record?.id) {
        Object.assign(
          formValues,
          type === 'update'
            ? {
                id: props.record?.id,
                titile: props.record?.titile,
                msgContent: props.record?.msgContent,
                msgType: props.record?.msgType,
                userNames: props.record?.userNames,
                userIds: props.record?.userIds?.split(',')
              }
            : props.record
        )
      }
      userTreeAjax()
    })

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          title={type === 'add' ? '新增' : '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={() => handleSubmitForm(1)}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; 保存
                  </ElButton>
                  <ElButton type="primary" onClick={() => handleSubmitForm(2)}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; 发布
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={formValues}>
            <ElRow>
              <ElCol span={24}>
                <ElFormItem
                  prop="titile"
                  label="通告标题"
                  rules={[{ required: true, message: '请输入通告标题' }]}
                >
                  {type === 'read' ? (
                    formValues.titile
                  ) : (
                    <ElInput v-model={formValues.titile} placeholder="请输入通告标题" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={24}>
                <ElFormItem
                  prop="msgContent"
                  label="通告内容"
                  rules={[{ required: true, message: '请输入通告内容' }]}
                >
                  {type === 'read' ? (
                    formValues.msgContent
                  ) : (
                    <ElInput
                      v-model={formValues.msgContent}
                      type="textarea"
                      placeholder="请输入通告内容"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  prop="msgType"
                  label="用户选择"
                  rules={[{ required: true, message: '请输入用户选择' }]}
                >
                  {type === 'read' ? (
                    formValues.msgType === 'USER' ? (
                      '指定用户'
                    ) : (
                      '全体用户'
                    )
                  ) : (
                    <ElRadioGroup v-model={formValues.msgType}>
                      {[
                        { id: 'USER', name: '指定用户' },
                        { id: 'ALL', name: '全体用户' }
                      ]?.map((item: any) => (
                        <ElRadio label={item.id}>{item.name}</ElRadio>
                      ))}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
              {formValues.msgType === 'USER' && (
                <ElCol span={12}>
                  <ElFormItem
                    prop="ids"
                    label="用户"
                    rules={[{ required: true, message: '请输入用户' }]}
                  >
                    {type === 'read' ? (
                      formValues.userNames
                    ) : (
                      <ElCascader
                        v-model={formValues.ids}
                        options={state.userTreeOpt}
                        props={propsCascader}
                        show-all-levels={false}
                        onChange={cascaderChange}
                        placeholder="请输入用户"
                      />
                    )}
                  </ElFormItem>
                </ElCol>
              )}
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
